﻿#include "scroll_mode_thread.h"
#include <QDebug>

void ScrollModeADCThread::start(Priority priority) {
  thread_is_running_ = true;
  QThread::start(priority);

  int channel_count = base_device_.toStrongRef()->GetADCLegalChannelSize();
  data_length_threshold_ = base_device_.toStrongRef()->GetCurrentDataLength();
  qDebug() << "data_length_threshold_ = " << data_length_threshold_;
  data_.resize(channel_count);
  for (int i = 0; i < data_.size(); i++) {
    data_[i].reserve(data_length_threshold_);
    data_[i].resize(data_length_threshold_);
  }
}

void ScrollModeADCThread::quit() {
  thread_is_running_ = false;
  QThread::wait();
  QThread::quit();
}

void ScrollModeADCThread::run() {
  qDebug() << "ScrollModeADCThread::run()";
  const auto base_device = base_device_.toStrongRef();
  int channel_count = base_device->GetADCLegalChannelSize();
  while (thread_is_running_) {
    for(int i = 0; i < channel_count; ++ i){
      auto temp_data = std::make_unique<float[]>(data_length_threshold_);
      bool success = base_device->TryReadADCData(i, temp_data.get(), data_length_threshold_);

      if(!thread_is_running_){
        break;
      }

      if (!success) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
        i --;
        continue;
      }

      for(int j = 0; j < data_length_threshold_; ++ j){
        data_[i][j] = temp_data[j];
      }
    }

    emit SendData(data_);
  }

}

bool ScrollModeADCThread::ReadADCData() {
  bool success = false;
  const auto base_device = base_device_.toStrongRef();
  const auto channel_number = base_device->GetADCLegalChannel().size();
  for (int i = 0; i < channel_number; i++) {
    float temp_data = 0;
    if (!base_device->TryReadADCData(i, &temp_data)) {
      continue;
    }

    data_[i].emplace_back(temp_data);
    success = true;
  }

  return success;
}
